package org.uni_hi.muus.replace.impl;

import java.io.IOException;
import java.util.Enumeration;
import java.util.Vector;

import javax.bluetooth.RemoteDevice;

import org.uni_hi.muus.bluetooth.BluetoothDiscovery;
import org.uni_hi.muus.replace.MuuSReplace;
import org.uni_hi.muus.server.WebServer;
import org.uni_hi.muus.server.util.ConfigRecordStore;
import org.uni_hi.muus.server.util.Query;
import org.uni_hi.muus.util.Configuration;

public class ConfigReplace implements MuuSReplace {
	
	private static final String 
		ROOT_DIR_PARAM="root_dir",
		BT_ID_PARAM="bt_id",
		BT_DEVS_PARAM="bt_devs",
		JAR_PATH_PARAM="jar_path";
	
	protected void processPOSTData(Query q){
		String t=(String)q.get(ROOT_DIR_PARAM);
		if(t!=null)ConfigRecordStore.setRootDirectory(t);
	}
	
	public byte[] getReplacement(Vector arg,Query q) {
		String sb=null;
		if(arg.contains("POST")&&q!=null){
			processPOSTData(q);
		}
		if(arg.contains(ROOT_DIR_PARAM)){
			sb=(ConfigRecordStore.getRootDirectory());
		}
		if(arg.contains(BT_ID_PARAM)){
			sb=Configuration.getLocalBTID();
		}
		if(arg.contains(BT_DEVS_PARAM)){
			sb=getBTDevs();
		}
		if(arg.contains(JAR_PATH_PARAM)){
			sb=getJarPath();
		}
		if(sb==null)sb="";
		return sb.getBytes();
	}
	
	private String getJarPath(){
		return System.getProperty("microedition.home");
	}
	
	private String getBTDevs(){
		Vector v=BluetoothDiscovery.getDeviceVector();
		String result="";
		Enumeration e=v.elements();
		RemoteDevice rd=null;
		while(e.hasMoreElements()){//address should be http://localhost:<port>/<btid>/
			rd=(RemoteDevice)e.nextElement();
			result+="<li><a class=\"btLink\" href=\""+WebServer.getServerAddress()+rd.getBluetoothAddress()+"/\">";
			try {
				result+=rd.getFriendlyName(false);
			} catch (IOException e1) {
				result+="RemoteDevice";
			}
			result+="</a></li>";
		}
		return result;
	}

	public String toString(){
		return this.getClass().getName()+": provides an interface to the RecordStore containing configuration Data.";
	}
}
